/*
 * Copyright (C) 2008 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.algorhythms.infinity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import java.util.Calendar;

public class CreateItemActivity extends Activity {

    private EditText mNameText;
    private EditText mLocationHint;
    private EditText mMoreInfo;
    private EditText mQuantity;
    //private Long mRowId;
    private ItemDbAdapter mDbHelper;
    private Long mCatId;
    //Button confirm_item;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.item_creation_layout);
        mDbHelper = ItemDbAdapter.getInstance(this);
        mDbHelper.open();

        mNameText = (EditText) findViewById(R.id.itemNameBox);
        mLocationHint = (EditText) findViewById(R.id.locationHintBox);
        mMoreInfo = (EditText) findViewById(R.id.itemInfoBox);
        mQuantity = (EditText) findViewById(R.id.itemQuantityBox);

        Bundle extras = getIntent().getExtras();
        /*mRowId = (savedInstanceState == null) ? null :
                (Long) savedInstanceState.getSerializable(ItemDbAdapter.KEY_ROWID);
        if (mRowId == null)
            mRowId = extras != null ? extras.getLong(ItemDbAdapter.KEY_ROWID)
                    : null;*/

        // Check the serializables for the cat id
        mCatId = (savedInstanceState == null) ? null :
                (Long) savedInstanceState.getSerializable(CategoryViewActivity.categoryIdKey);

        if(mCatId == null) {
            // Get the category Id
            mCatId = extras != null ? extras.getLong(CategoryViewActivity.categoryIdKey) : null;

            // If category Id is null some glitch has occured, finish this activity
            if(mCatId == null)
                finish();
        }

        CategoryDbAdapter categoryAdapter = CategoryDbAdapter.getInstance(this);
        categoryAdapter.open();

        Cursor item = categoryAdapter.fetchCategory(mCatId);
        startManagingCursor(item);
        TextView title = (TextView)findViewById(R.id.itemHeader);
        title.setText("Add item to " + item.getString(item.getColumnIndexOrThrow(CategoryDbAdapter.KEY_CATNAME)));

        //populateFields();
    }

    /*   private void populateFields() {
        if (mRowId != null) {
            Cursor item = mDbHelper.fetchItem(mRowId);
            startManagingCursor(item);
            mNameText.setText(item.getString(
                    item.getColumnIndexOrThrow(ItemDbAdapter.KEY_ITEMNAME)));
            mLocationHint.setText(item.getString(
                    item.getColumnIndexOrThrow(ItemDbAdapter.KEY_LOCATIONHINT)));
            mMoreInfo.setText(item.getString(
                    item.getColumnIndexOrThrow(ItemDbAdapter.KEY_EXTRAINFO)));
            mChecked.setChecked(item.getInt(
                    item.getColumnIndexOrThrow(ItemDbAdapter.KEY_CHECKED)) != 0);
            mQuantity.setSelection(1);
        }
    }*/

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if(hasValidFields()) {
            saveState();
            outState.putSerializable(CategoryViewActivity.categoryIdKey, mCatId);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(hasValidFields())
            saveState();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //populateFields();
    }

    private void saveState() {
        String itemName = mNameText.getText().toString();
        String locationHint = mLocationHint.getText().toString();
        long quantity = Long.parseLong(mQuantity.getText().toString());
        String info = mMoreInfo.getText().toString();

        mDbHelper.createItem(itemName, mCatId, quantity, locationHint, info);
    }

    public void confirmItem(View view) {
        String itemName = mNameText.getText().toString();

        if(itemName == null || "".equals(itemName.trim())) {
            showAlert("You need a valid name for your item!");
            return;
        }

        try {
            Integer.parseInt(mQuantity.getText().toString());
        }
        catch(NumberFormatException e) {
            showAlert("You need to enter a number for the quantity!");
            return;
        }


        setResult(RESULT_OK);
        finish();
    }

    /**
     * @return True if the entered fields are valid; false otherwise.
     */
    private boolean hasValidFields() {
        String itemName = mNameText.getText().toString();

        if (itemName == null || itemName.trim().equals("")) {
            return false;
        }

        try {
            String quantity = mQuantity.getText().toString();
            Integer.parseInt(quantity);
        }
        catch (NumberFormatException e) {
            return false;
        }

        return true;
    }

    private void showAlert(String msg) {
        new AlertDialog.Builder(this)
                .setIcon(android.R.drawable.ic_dialog_alert)
                .setTitle("Error!")
                .setMessage(msg)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ;
                    }
                }).show();
    }
}